package cn.regexp.greenway.service;

import cn.hutool.http.HttpStatus;
import cn.regexp.greenway.pojo.Route;
import cn.regexp.greenway.utils.UserThreadLocal;
import cn.regexp.greenway.vo.ErrorResult;
import com.mongodb.client.result.UpdateResult;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;

@Service
public class RouteService {

    @Autowired
    private MongoTemplate mongoTemplate;

    @Autowired
    private BaiduService baiduService;

    @Autowired
    private RouteInfoService routeInfoService;

    /**
     * 创建路线
     *
     * @return
     */
    public String createRoute() {
        Route route = new Route();
        route.setId(ObjectId.get());
        route.setUserId(UserThreadLocal.get());
        route.setStatus(1);
        route.setIsShare(false); //默认不投稿
        route.setStartTime(System.currentTimeMillis());

        //将数据保存到MongoDB
        this.mongoTemplate.save(route);

        String routeId = route.getId().toString();
        //百度地图鹰眼服务中创建Entity
        Boolean bool = this.baiduService.createEntity(routeId);
        if (bool) {
            //成功
            return routeId;
        }

        //失败
        return null;
    }

    /**
     * 删除路线
     *
     * @param routeId 路线id
     * @return
     */
    public Boolean deleteRoute(String routeId) {
        //删除MongoDB中的数据
        Query query = this.createQuery(routeId);
        boolean result = this.mongoTemplate.remove(query, Route.class).getDeletedCount() == 1;
        if (result) {
            //删除百度鹰眼服务中的实体
            if (this.baiduService.deleteEntity(routeId)) {
                return true;
            }
        }
        return false;
    }

    /**
     * 构造查询对象，设置了2个条件，其中userId是确保只删除自己的数据
     *
     * @param routeId
     * @return
     */
    private Query createQuery(String routeId) {
        return Query.query(Criteria.where("id").is(new ObjectId(routeId))
                .and("userId").is(UserThreadLocal.get()));
    }

    /**
     * 更新路线（结束运动）
     * @param routeId   路线ID
     * @param title     路线标题
     * @return
     */
    public Object updateRoute(String routeId, String title) {
        // 判断路线是否已经结束，如果已经结束则不能再次结束
        Route route = queryRouteById(routeId);
        if (route == null) {
            return ErrorResult.builder()
                    .errCode(String.valueOf(HttpStatus.HTTP_INTERNAL_ERROR))
                    .errMessage("结束运动失败，路线不存在！")
                    .build();
        }

        if (route.getStatus() == 0) {
            return ErrorResult.builder()
                    .errCode(String.valueOf(HttpStatus.HTTP_BAD_REQUEST))
                    .errMessage("结束运动失败，该路线已经结束！")
                    .build();
        }

        // 更新路线数据
        Update update = Update.update("title", title).set("status", 0)
                .set("endTime", System.currentTimeMillis());


        UpdateResult result = mongoTemplate.updateFirst(createQuery(routeId), update, Route.class);
        if (result.getModifiedCount() == 1) {
            // 查询百度地图鹰眼服务中的路线轨迹点，异步更新到路线数据中
            routeInfoService.updateRouteInfo(routeId, UserThreadLocal.get());

            // 更新成功
            return null;
        }

        return ErrorResult.builder()
                .errCode(String.valueOf(HttpStatus.HTTP_BAD_REQUEST))
                .errMessage("结束运动失败，更新异常！")
                .build();
    }

    public Route queryRouteById(String routeId) {
        return mongoTemplate.findById(new ObjectId(routeId), Route.class);
    }
}
